<template>
    <!--上传图片-->
    <div class="ui-picture">
        <div class="ui-picture-content ui-img-upload-model">
            <el-scrollbar style="height:100%;width:100%">
                <el-form
                    ref="form"
                    :model="form"
                    :rules="formRules"
                    label-width="80px"
                    style="width:100%;"
                >
                    <el-form-item label="选择分组" prop="">
                        <el-select
                            style="width:200px;"
                            v-model="form.groupId"
                            placeholder="选择分组"
                        >
                            <el-option
                                v-for="(item, index) of allImageGroup"
                                :key="index"
                                :label="item.groupName"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上传图片">
                        <div class="ui-image-list">
                            <div
                                class="ui-image-item"
                                v-for="(item, index) of form.files"
                                :key="index"
                            >
                                <img
                                    src="../../assets/basic/delete.png"
                                    @click="deleteImg(index)"
                                    style="width:14px;height:14px;position: absolute;top:0;right:0;cursor: pointer;z-index: 10;"
                                />
                                <div
                                    class="ui-image-item-img"
                                    :style="{
                                        'background-image': 'url(' + imgPreList[index] + ')'
                                    }"
                                ></div>
                                <div class="ui-image-item-name">
                                    <el-input v-model="item.fileName" placeholder="" />
                                </div>
                                <div class="ui-img-error" v-if="errorVisible">
                                    <span style="color:red;font-size:13px;">失败</span>
                                </div>
                            </div>
                            <div class="ui-image-item" v-if="form.files.length < 8">
                                <el-upload
                                    class="upload-demo ui-upload-button-img"
                                    :auto-upload="false"
                                    action="http://localhost:8080"
                                    multiple
                                    ref="upload"
                                    :on-change="handleChange"
                                    :file-list="fileList"
                                >
                                    <i class="fa fa-plus" style="font-size: 37px;color:#bbb;"></i>
                                </el-upload>
                            </div>
                        </div>
                        <div class="ui-upload-remind">
                            <div>注意：1、图片支持格式png、jpg、GIF、BMP、JPEG格式</div>
                            <div style="padding-left:37px;box-sizing: border-box;">
                                2、图片大小不得超过2M
                            </div>
                            <div style="padding-left:37px;box-sizing: border-box;">
                                3、一次最多上传8张图片
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <div style="text-align: center;">
                    <el-button
                        type="primary"
                        :loading="loading"
                        class="ui-button"
                        @click="submitAllImg(0)"
                        >确定</el-button
                    >
                    <el-button class="ui-button" @click="cancleImg">取消</el-button>
                </div>
            </el-scrollbar>
        </div>
    </div>
</template>

<script>
import { uploadImage, queryConditionList, queryAllImageGroup } from '@/api/image';
import { alertSuccess, alertError, alertWarning, formatTime } from '@/utils/index';
export default {
    data() {
        return {
            fileList: [],
            allImageGroup: [],
            imgPreList: [],
            loading: false,
            errorList: [],
            errorVisible: false,
            form: {
                groupId: '',
                files: []
            },
            formRules: {
                groupId: [{ required: true, trigger: 'change', message: '请输入分组' }]
            },
            url: require('../../assets/basic/timg111.jpg')
        };
    },
    methods: {
        // *********************************** 公共方法 *****************************************
        filterNullFields(options) {
            // 删除空字段
            let param = Object.assign(options);
            if (Object.keys.length > 0) {
                for (let key in param) {
                    if (!param[key] && param[key] !== 0) {
                        delete param[key];
                    }
                }
            }
            return param;
        },
        getQueryParam(value) {
            // 获取查询字段参数 ٩(๑❛ᴗ❛๑)۶
            let model = this.searchModel;
            let options = {};
            for (const key in model) {
                if (key !== 'checkInTime') {
                    Object.assign(options, { [key]: model[key] });
                }
                delete model.currentPage;
            }
            let time = {};
            if (Array.isArray(model.checkInTime) && model.checkInTime.length) {
                time = {
                    startRegTime: formatTime(new Date(model.checkInTime[0])),
                    endRegTime: formatTime(new Date(model.checkInTime[1]))
                };
            }
            let param = Object.assign({}, time, options, value);
            return this.filterNullFields(param);
        },
        // *********************************** 页面逻辑 *****************************************
        initPageData() {
            // 初始化页面数据 包括下拉菜单的选项以及表格数据
            // 这个参数拿的也太费劲了╭(╬◣д◢) 必须写在setTimeout里 否则娶不到model下的数据(╰_╯)#会报错
            setTimeout(() => {
                let initTableParm = { ...{ pageNum: 1, pageSize: 10 } };
                Promise.all([this.getAllImageGroup()])
                    .then(res => {})
                    .catch(err => {
                        console.log('err', err);
                    });
            });
        },
        handleChange(file, fileList) {
            let image = file.raw;
            let fileName = file.name;
            let obj = {
                file: image,
                fileName: fileName.split('.')[0]
            };
            if (this.form.files.length < 8) {
                this.form.files.push(obj);
            }
            if (file) {
                let reader = new FileReader();
                let that = this;
                reader.readAsDataURL(file.raw);
                reader.onload = function(e) {
                    // 这里的this 指向reader
                    if (that.imgPreList.length < 8) {
                        that.imgPreList.push(this.result);
                    }
                };
            }
            /*let array = []
        array.push(obj)
        let data = {
          files:array,
          groupId:this.searchModel.groupId
        }*/
            /**/
        },
        deleteImg(index) {
            this.form.files.splice(index, 1);
            this.imgPreList.splice(index, 1);
        },
        submitAllImg(param) {
            this.loading = true;
            if (param == 0) {
                this.errorList = [];
            }
            if (this.form.files.length > 0) {
                let num = 0;
                if (param != undefined) {
                    num = param;
                }
                let array = [];
                array.push(this.form.files[num]);
                let data = {
                    groupId: this.form.groupId,
                    files: array
                };
                uploadImage(this.filterNullFields(data))
                    .then(res => {
                        // 请求接口
                        if (res.data.success) {
                            if (num + 1 == this.form.files.length) {
                                this.loading = false;
                                if (this.errorList.length == 0) {
                                    alertSuccess('添加图片成功', this);
                                    this.$emit('refresh');
                                } else {
                                    alertError('添加图片不能大于2M', this);
                                    let array1 = [];
                                    let array2 = [];
                                    this.errorList.forEach((item2, index2) => {
                                        array1.push(this.form.files[item2]);
                                        array2.push(this.imgPreList[item2]);
                                    });
                                    this.form.files = array1;
                                    this.imgPreList = array2;
                                }
                            } else if (num + 1 < this.form.files.length) {
                                this.submitAllImg(num + 1);
                            }
                        } else {
                            this.errorList.push(num);
                            if (num + 1 == this.form.files.length) {
                                alertError('添加图片不能大于2M', this);
                                this.loading = false;
                                if (this.errorList.length > 0) {
                                    let array1 = [];
                                    let array2 = [];
                                    this.errorList.forEach((item2, index2) => {
                                        array1.push(this.form.files[item2]);
                                        array2.push(this.imgPreList[item2]);
                                    });
                                    this.form.files = array1;
                                    this.imgPreList = array2;
                                }
                            } else if (num + 1 < this.form.files.length) {
                                this.submitAllImg(num + 1);
                            }
                            //alertError(res.data.msg,this)
                            //this.loading = false
                        }
                    })
                    .catch(err => {
                        //alertError('添加图片失败',this)
                        //this.loading = false
                        this.errorList.push(num);
                        if (num + 1 == this.form.files.length) {
                            alertError('添加图片不能大于2M', this);
                            this.loading = false;
                            if (this.errorList.length > 0) {
                                let array1 = [];
                                let array2 = [];
                                this.errorList.forEach((item2, index2) => {
                                    array1.push(this.form.files[item2]);
                                    array2.push(this.imgPreList[item2]);
                                });
                                this.form.files = array1;
                                this.imgPreList = array2;
                            }
                        } else if (num + 1 < this.form.files.length) {
                            this.submitAllImg(num + 1);
                        }
                    });
                /*this.form.files.forEach((item,index) => {

          })*/
            } else {
                alertWarning('请先选择图片', this);
                this.loading = false;
            }
        },
        getAllImageGroup() {
            queryAllImageGroup()
                .then(res => {
                    // 请求接口
                    if (res.data.success) {
                        this.allImageGroup = res.data.data;
                    } else {
                        alertError(res.data.msg, this);
                    }
                })
                .catch(err => {
                    console.log('err', err);
                });
        },
        viewImg(fileObj) {
            return window.URL.createObjectURL(fileObj);
        },
        cancleImg() {
            this.$emit('close');
        }
    },
    mounted() {
        this.initPageData();
    },
    computed: {},
    watch: {}
};
</script>
<style lang="scss">
.ui-upload-button-img .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.ui-img-upload-model .el-scrollbar {
    padding-bottom: 0 !important;
}
</style>
<style scoped lang="scss">
.ui-picture {
    height: auto !important;
    .ui-picture-content {
        width: 100%;
        height: 450px;
        display: flex;
    }
}
.ui-button {
    width: 80px;
    height: 30px;
    padding: 0;
    margin-right: 10px;
}
.ui-image-list {
    width: 100%;
    overflow: hidden;
    .ui-image-item {
        width: calc(25% - 16px);
        float: left;
        margin-bottom: 15px;
        margin-right: 15px;
        position: relative;
        .ui-image-item-img {
            width: 100%;
            height: 100px;
            background-repeat: no-repeat;
            background-size: cover;
            background-position: center center;
        }
        .ui-image-item-name {
            margin-top: 10px;
        }
    }
}
.ui-upload-button-img {
    width: 100%;
    height: 100px;
    border: 1px solid #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
}
.ui-upload-remind {
    font-size: 12px;
    color: #aaa;
    margin-top: 15px;
    div {
        line-height: 20px;
    }
}
.ui-img-error {
    position: absolute;
    z-index: 2;
    left: 0;
    top: 0;
    width: 100%;
    height: 100px;
    background: rgba(0, 0, 0, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
    img {
        max-height: 100%;
    }
}
</style>
